@extends('layouts._app')
@section('content')
    <style>
        .email-wrap {
            background-color: #fff;
        }

        .login {
            cursor: pointer;
        }

        #login {
            padding: 0 25px 0 6px;
            height: 42px;
            line-height: 42px;
            border-bottom: 1px solid #ff5722;
            font-size: 14px;
            color: #ffffff;
            overflow: hidden;
            background-color: #1E9FFF;
            border-radius: 2px 2px 0 0;
        }

        .pl {
            width: 90%;
            border: 1px solid #e8e8e8;
            padding: 4px;
            border-radius: 5px;
            position: relative;
            margin: 20px 0 0 75px;
        }

        .tx {
            position: absolute;
            top: 0;
            left: -63px;
            width: 50px;
            height: 50px;
            background-image: url(/static/admin/icon/tx.png);
            background-repeat: no-repeat;
            background-position: right 20px;
            padding-right: 12px;
        }

        .pl a {
            color: #5d6c80;
            text-decoration: none;
            cursor: pointer;
        }

        .tx img {
            width: 100%;
            border-radius: 45px;
        }

        .pl ul {
            padding: 0 20px;
            line-height: 26px;
        }

        .plbg {
            background-color: #fafafa;
            border-bottom: 1px dotted #DCDCDC;
        }

        .plbg .jl {
            float: right;
        }

        .dr {
            clear: right;
        }

        .pl .plul {
            word-wrap: break-word;
            padding-top: 10px;
            padding-bottom: 10px;
            font-size: 14px;
            background-color: #fafafa;
        }

        .pl ul {
            padding: 0 20px;
            line-height: 26px;
        }

        #LAY_demo1 {
            border-radius: 4px;
            line-height: 1.8;
            font-size: 16px;
            background-color: #fff;
            padding-top: 10px;
        }

    </style>
    <body class="iframe-h">

    <div class="wrap-container email-wrap clearfix">
        <ul class="layui-fixbar">
            <li class="layui-icon layui-fixbar-top" id="layui-fixbar-top" onclick="topFunction()"
                style="display:none;">
            </li>
        </ul>
        @include('layouts._flash')

        <fieldset class="layui-elem-field site-demo-button" style="margin-top: 30px;">
            <legend>房间号{{$request['room_id']}}</legend>

            <div style="padding: 15px;">
                @foreach($room as $value)
                    <a class="layui-btn layui-btn-normal room_title"
                       href="{{route('expansion.chat.index')}}?room_id={{$value->id}}&title={{$value->title}}"
                       data-id="{{$value->id}}">{{$value->title}}</a>
                @endforeach
                {!! Form::open(['route' => 'expansion.chat.room','class'=>'layui-form','style'=>'float: right;','method'=>'get']) !!}
                <div class="layui-inline">
                    <select id="change_category" lay-filter="category" lay-search
                            data-id="chats">
                        <option selected>下载</option>
                        <option>.txt</option>
                        <option>.xlsx</option>
                    </select>
                </div>
                {!! Form::text('title',"{$request->title}",['class'=>'layui-input-block','id'=>'room','placeholder'=>'输入房间名称']) !!}
                {!! Form::submit('添加房间',['class'=>'layui-btn']) !!}
                <button id="del" type="button" class="layui-btn layui-btn-sm layui-btn-normal"><i
                        class="layui-icon"></i>
                    删除房间
                </button>
                {!! Form::close() !!}
            </div>
        </fieldset>
        <div id="login">
        </div>
        <script>
            function logRemove() {
                $('#login').attr('style', 'display:none;');
            }
        </script>
        {!! Form::open(['class'=>'layui-form','style'=>'width: 90%;padding-top: 20px;']) !!}

        <div class="layui-form-item button"
             style="height:700px; overflow: auto;width:70%;display: inline-block;float: left;"
             id="LAY_demo1">

        </div>
        <div id="user" style="height: -webkit-fill-available; overflow: auto;width:30%;display: inline-block;">
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">@</label>
            <div class="layui-input-inline" style="width: 60%">
                <select name="interest" id="cli_all" class="layui-select">
                    <option value="0">所有人</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">内容</label>
            <div class="layui-input-inline" style="width: 60%">
                <div id="markdown">
                    {!! Form::textarea('content','',['id'=>'content','class'=>'layui-textarea','rows'=>'10']) !!}
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-inline" style="margin-left: 60%;">
                <button type="button" class="layui-btn layui-btn-normal" lay-filter='siteInfo' id="submit">立即发送</button>
            </div>
        </div>
        {!! Form::close() !!}
    </div>
    <script src="{{asset('static/admin/layui/layui.js')}}" type="text/javascript" charset="utf-8"></script>
    <script src="{{asset('static/admin/js/common.js')}}" type="text/javascript" charset="utf-8"></script>
    <script src="{{asset('js/jquery.min.js')}}" type="text/javascript" charset="utf-8"></script>
    <script src="{{asset('js/jquery.base64.js')}}" type="text/javascript" charset="utf-8"></script>
    <script src="{{asset('js/common.js')}}" type="text/javascript" charset="utf-8"></script>
    <script>
        function topFunction() {
            $(".button").animate({scrollTop: 0}, "slow");
            $('#layui-fixbar-top').attr('style', 'display:none;');
        }

        function scrollFun() {
            var div = document.getElementsByClassName('button')[0];
            var layuiBodyScrollTop = div.scrollTop;
            if (layuiBodyScrollTop > 200) {
                document.getElementById("layui-fixbar-top").style.display = "block";
            } else {
                document.getElementById("layui-fixbar-top").style.display = "none";
            }
        }

        /*注册事件*/
        if (document.addEventListener) {
            document.addEventListener('DOMMouseScroll', scrollFun, false);
        }//W3C
        window.onmousewheel = document.onmousewheel = scrollFun;//IE/Opera/Chrome

        layui.use(['form', 'jquery', 'layedit', 'dialog'], function () {
            var form = layui.form(),
                $ = layui.jquery;
            var dialog = layui.dialog;
            $(function () {
                    var div = document.getElementsByClassName('button')[0];
                    div.scrollTop = div.scrollHeight;


                    $(".room_title").click(function () {
                        $("#room").val($(this).text());
                    })
                    $('#del').click(function () {
                        var title = $("#room").val();

                        $.ajax({
                            type: 'post',
                            url: '{{route('expansion.chat.destroy')}}',
                            dataType: 'json',
                            data: {
                                title: title,
                            },
                            beforeSend: function () {
                                layer.load(1, {
                                    shade: [0.1, '#333333'] //0.1透明度的白色背景
                                });
                            },
                            error: function (xhr) {//获取ajax的错误信息
                                layer.alert(xhr.responseText, "Failed", function () {
                                    layer.closeAll();
                                });
                            },
                            complete: function (XHR) {
                                XHR = null;
                            },
                            success: function (msg) {
                                layer.closeAll();
                                if (msg.code == 403) {
                                    layer.msg(msg.msg, {icon: 4, time: 3000});
                                }
                                if (msg.code != 200) {
                                    layer.msg(msg.msg, {icon: 5, time: 3000});
                                }
                                layer.msg(msg.msg, {icon: 1, time: 3000}, function () {
                                    window.location.reload();
                                });
                            }
                        })
                    });

                    connect();
                    var ws, res, client_list = {};

                    // 连接服务端
                    function connect() {
                        ws = new WebSocket("ws://127.0.0.1:8282");
                        ws.onopen = onopen;
                        // 当有消息时根据消息类型显示不同信息
                        ws.onmessage = onmessage;
                        ws.onclose = function () {
                            connect();
                        };
                    }


                    // 连接建立时发送登录信息
                    function onopen() {
                        var login_data = '{"type":"login","client_name":"{{Auth::id()}}","room_id":"{{$request['room_id']}}"}';
                        ws.send(login_data);
                    }

                    // 服务端发来消息时
                    function onmessage(e) {
                        var data = JSON.parse(e.data);
                        switch (data['type']) {
                            case 'ping':
                                ws.send('{"type":"pong"}');
                                break;
                            // 登录 更新用户列表
                            case 'login':
                                say(data['client_name'] + '加入聊天室');
                                if (data['client_list']) {
                                    client_list = data['client_list'];
                                } else {
                                    client_list[data['client_id']] = [data['client_uid'], data['client_name'], data['image']];
                                }
                                if (data['res']) {
                                    res = data['res'];
                                } else {
                                    res = '';
                                }
                                says();
                                flush_select();
                                break;
                            // 发言
                            case 'say':
                                saye(data['from_client_id'], data['from_client_name'], data['content'], data['created_at'], data['image']);
                                break;
                            // 用户退出 更新用户列表
                            case 'logout':
                                say(data['from_client_name'] + ' 退出了');
                                delete client_list[data['from_client_id']];
                                flush_select();
                        }
                    }

                    //新增消息
                    // 发言
                    function saye(from_client_id, from_client_name, content, time, image) {
                        var html = '<div class="pl"><div class="tx">' +
                            '<a href="#">' +
                            '<img alt="' + from_client_name + '" src="' + image + '"></a></div>' +
                            '<ul class="plbg">' +
                            '<div class="f z13">' + from_client_name + '<span class="jl">' + time + '</span></div>' +
                            '</ul><ul class="plul"><pre>' + content + '</pre></ul></div>';

                        $("#LAY_demo1").append(html);
                        var div = document.getElementById('LAY_demo1');
                        div.scrollTop = div.scrollHeight;
                    }

                    //发送聊天信息
                    $("#submit").on("click", function () {
                        var value = $.trim($('#content').val());

                        if (value == '') {
                            layer.msg('请输入要发送的内容');
                            return false;
                        }
                        var to_client_id = $("#cli_all").val();
                        var to_client_name = $("#cli_all option:selected").text();
                        ws.send('{"type":"say","to_client_id":"' + to_client_id + '","id":"' + {{Auth::id()}} +'","to_client_name":"' + to_client_name + '",' +
                            '"content":"' + value + '"}');
                        $('#content').val('');

                    });

                    $(document).keydown(function (e) {
                        if (e.keyCode === 13 && e.ctrlKey) {
                            $("#submit").trigger("click");
                        }
                    });

                    //显示消息
                    function says() {
                        var html = '';
                        for (var i = 0; i < res.length; i++) {
                            if (res[i]['client_name'] == 'all') {
                                html += '<div class="pl"><div class="tx">' +
                                    '<a href="#">' +
                                    '<img alt="' + res[i]['name'] + '" src="' + res[i]['image'] + '"></a></div>' +
                                    '<ul class="plbg">' +
                                    '<div class="f z13">' + res[i]['name'] + '<span class="jl">' + res[i]['created_at'] + '</span></div>' +
                                    '</ul><ul class="plul"><pre>' + res[i]['content'] + '</pre></ul></div>';
                            } else if (res[i]['client_name'] != 'all' && res[i]['client_name'] == '{{Auth::id()}}') {
                                if (res[i]['client_name'] != 'all' && res[i]['name'] == '{{Auth::user()->name}}') {
                                    html += '<div class="pl"><div class="tx">' +
                                        '<a href="#">' +
                                        '<img alt="' + res[i]['name'] + '" src="' + res[i]['image'] + '"></a></div>' +
                                        '<ul class="plbg">' +
                                        '<div class="f z13">' + res[i]['name'] + '<span class="jl">' + res[i]['created_at'] + '</span></div>' +
                                        '</ul><ul class="plul"><p><b>你对' + res[i]['client_names'] + '说:</b><pre>' + res[i]['content'] + '</pre></ul></div>';
                                }

                                html += '<div class="pl"><div class="tx">' +
                                    '<a href="#">' +
                                    '<img alt="' + res[i]['name'] + '" src="' + res[i]['image'] + '"></a></div>' +
                                    '<ul class="plbg">' +
                                    '<div class="f z13">' + res[i]['name'] + '<span class="jl">' + res[i]['created_at'] + '</span></div>' +
                                    '</ul><ul class="plul"><p>' + '<b>对你说:</b><pre>' + res[i]['content'] + '</pre></ul></div>';
                            } else if (res[i]['client_name'] != 'all' && res[i]['name'] == '{{Auth::user()->name}}') {
                                html += '<div class="pl"><div class="tx">' +
                                    '<a href="#">' +
                                    '<img alt="' + res[i]['name'] + '" src="' + res[i]['image'] + '"></a></div>' +
                                    '<ul class="plbg">' +
                                    '<div class="f z13">' + res[i]['name'] + '<span class="jl">' + res[i]['created_at'] + '</span></div>' +
                                    '</ul><ul class="plul"><p>' + '<b>你对' + res[i]['client_names'] + '说:</b><pre>' + res[i]['content'] + '</pre></ul></div>';
                            }
                        }
                        $("#LAY_demo1").append(html);
                        var div = document.getElementById('LAY_demo1');
                        div.scrollTop = div.scrollHeight;
                    }


                    //添加登陆成功信息
                    function say(content) {
                        content = content + '<a class="login" onclick="logRemove()" style="float: right;" href="javascript:void(0);">&times;</a>'
                        $("#login").html(content);
                        $("#login").attr('style', 'dispaly:block;');
                    }

                    // 刷新用户列表框
                    function flush_select() {
                        $("#cli_all").html('');
                        $("#user").html('');
                        var caking = '';
                        var king = '<option value="all">所有人</option>';
                        for (var p in client_list) {
                            caking += '<img alt="' + client_list[p][1] + '" style="width: 50px;height: 50px;border-radius: 50%;padding: 10px;cursor: pointer;" class="layui-nav-img" src="' + client_list[p][2] + '" title="' + client_list[p][1] + '">';
                            king += '<option value="' + p + '">' + client_list[p][1] + '</option>';
                        }
                        $("#cli_all").append(king);
                        $("#user").append(caking);
                        form.render();
                    }

                }
            );
            form.on('select(category)', function (e) {
                if (e.value == '下载') {
                    return false;
                }
                /**
                 * 写入文件下载
                 * @param id
                 */
                var table = $("#change_category").data('id');
                var ext = e.value;
                dialog.confirm({
                    message: '这可能会耗费很长时间！是否继续',
                    success: function () {
                        window.open('{{route('TextFile')}}' + '?table=' + table + '&ext=' + ext, '_parent');
                        window.location.reload();
                    },
                });
            });
        })
    </script>
    </body>
@endsection
